package com.itheima.health.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.health.POJO.User;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.CustomerException;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@Slf4j
@EnableWebMvc
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest request;
    /**
     * @description 登录功能
     * @date 2021/11/29 10:45
     * @param username:
     * @param password:
     * @return com.itheima.health.entity.Result
     */
    @PostMapping("/login.do")
    public String login(String username,String password){
        log.info("正在进行登陆功能");
        //1.检验用户是否为空
        if(username==null || password==null || username=="" || password==""){
//            return new Result(false,"参数异常");
        }

        //2.用户不为null，将密码修改为md5加密格式
        //使用md5工具类加密
        password=DigestUtils.md5DigestAsHex(password.getBytes());
        //2.调用service方法判断用户名和密码是否匹配
        User realUser = userService.login(username,password);
        //3.登陆成功将用户id存入session域中
        if(realUser==null){
//            return new Result(false,"用户名不存在或用户名和密码不匹配");
        }
        HttpSession session = request.getSession();
        session.setAttribute("user",realUser.getId());

        return "/pages/main.html";
    }
}
